package jee.boot.module.file.attachment.rest;

import io.swagger.annotations.ApiOperation;
import jee.boot.common.basic.CrudController;
import jee.boot.common.basic.result.ResponseMessage;
import jee.boot.common.basic.result.Result;
import jee.boot.entity.file.Attachment;
import jee.boot.module.file.attachment.service.AttachmentService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 附件Controller
 * 
 * @author zhilei.wang
 * @version 2018-01-25
 */
@RestController
@RequestMapping(value = "/attachment")
public class AttachmentRestController extends CrudController<AttachmentService, Attachment> {
	/**
	 * 上传附件
	 * 
	 * @param file
	 * @return
	 */
//	@RequiresPermissions("system:attachment:upload")
	@PostMapping("/upload")
	@ApiOperation(value = "附件上传")
	public ResponseMessage<Attachment> upload(@RequestParam("file") MultipartFile file) {
		if (file == null) {
			return Result.requestError("上传的文件为空");
		}
		try {
			Attachment upload = service.upload(file);
			return Result.success(upload);
		} catch (IOException e) {
			e.printStackTrace();
			return Result.serverError(e.getMessage());
		}
	}

	/**
	 * 下载附件
	 * 
	 * @param entity
	 * @return
	 * @throws Exception
	 */
//	@RequiresPermissions("system:attachment:download")
	@PostMapping("/download")
	@ApiOperation(value = "附件下载")
	public void download(HttpServletRequest request, HttpServletResponse response, @RequestBody Attachment entity) throws Exception {
		try {
			service.download(request, response, entity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("下载文件失败:" + e.getMessage());
		}
	}

	/**
	 * 下载附件
	 * 
	 * @param entity
	 * @return
	 * @throws Exception
	 */
//	@RequiresPermissions("system:attachment:download")
	@GetMapping("/download")
	@ApiOperation(value = "附件下载")
	public void downloadGet(HttpServletRequest request, HttpServletResponse response, @ModelAttribute Attachment entity) throws Exception {
		try {
			service.download(request, response, entity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("下载文件失败:" + e.getMessage());
		}
	}


}